package com.benjaminwan.seriallibrary

import android.util.Log
import java.io.File

/**
 * cat /proc/tty/drivers
 * /dev/console         /dev/console    5       1 system:console
 * /dev/ptmx            /dev/ptmx       5       2 system
 * rfcomm               /dev/rfcomm   216 0-255 serial
 * usbserial            /dev/ttyUSB   188 0-511 serial
 * acm                  /dev/ttyACM   166 0-31 serial
 * msm_serial_hs        /dev/ttyHS    246 0-255 serial
 * 驱动名、默认的节点名、驱动主编号、驱动次编号范围、tty驱动类型
 */

data class SerialDriver(
    val name: String,
    val node: String,
    val major: String,
    val minor: String,
    val type: String
) {
    companion object {
        private const val TAG = "SerialPort"
    }

    val findDevices: List<File>
        get() {
            val dev = File("/dev")
            if (!dev.exists()) {
                Log.i(TAG, "getDevices: ${dev.absolutePath} 不存在 ")
                return emptyList()
            }
            if (!dev.canRead()) {
                Log.i(TAG, "getDevices: ${dev.absolutePath} 没有读取权限")
                return emptyList()
            }
            val files = try {
                dev.listFiles()
            } catch (e: Exception) {
                emptyArray<File>()
            }
            return files.filter { it.absolutePath.startsWith(node) }
        }
}
